package com.huazai.study;

import java.lang.reflect.Method;

public class 普通方法_反射方法的性能比较 {
    public static void main(String[] args) throws Exception {
        test01();
        test02();
        test03();
    }

    public static void test01() {
        User user = new User();
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 1000000000; i++) {
            user.getName();
        }
        long endTime = System.currentTimeMillis();
        System.out.printf("普通方法，This program had cost %d ms",endTime - startTime);
        System.out.println();

    }
    public static void test02() throws Exception {

        Class<?> c1 = Class.forName("com.huazai.study.User");
        User user = (User) c1.getDeclaredConstructor().newInstance();
        Method getName = c1.getMethod("getName");

        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 1000000000; i++) {
            getName.invoke(user);
        }
        long endTime = System.currentTimeMillis();

        System.out.printf("反射机制，This program had cost %d ms",endTime - startTime);
        System.out.println();
    }
    public static void test03() throws Exception {
        User preUser = new User();
        Class<? extends User> c1 = preUser.getClass();
        User user = (User) c1.getDeclaredConstructor().newInstance();
        Method getName = c1.getMethod("getName");
        getName.setAccessible(true);

        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 1000000000; i++) {
            getName.invoke(user);
        }
        long endTime = System.currentTimeMillis();

        System.out.printf("反射机制(关闭安全性检查),This program had cost %d ms",endTime - startTime);
        System.out.println();
    }

}